% Change to project folder
cd('C:\Users\Dani\Desktop\CV project')

% CONSTANTS
descriptorN = 20;
cupThreshold = 20;
sceneThreshold = 25;

% We read the image
cup = imread('cup.png');

% First, let's see the histogram of the image
imhist(cup)
axis([0 255 0 80])

% SEGMENTATION AND CLEANING UP

% We need to segment the image from the background, using basic (threshold = 25)
tcup = basicThresholding(cup, cupThreshold);
% Let's try with erosion
erodeCup = imerode(tcup, strel('square', 3));

% INNER BORDER TRACING BORDER

% Inner boundary tracing algorithm
cupBorder = innerBorder(erodeCup, 1);
 
 % SCENE
 
 % Segmentation and cleaning up of the scene
scene = imread('scene.png');
imhist(scene);
axis([0 255 0 900])
tscene = basicThresholding(scene, sceneThreshold);
erodeScene = imerode(tscene, strel('diamond', 3));
finalScene = imdilate(erodeScene, strel('square', 3));

% Now we separate and label the objects
[objects num ] = bwlabel(finalScene);

% Descriptors

values = [15 20 30 45 65 95 125 160 200];
tDist = [];

for v = 1:size(values, 2)
    cupDescriptor = getDescriptor(cupBorder, values(v));

    sceneDescriptors = []
    for currentObject = 1:num
        currentBorder = innerBorder(objects, currentObject);
        sceneDescriptors = [sceneDescriptors ; getDescriptor(currentBorder, values(v))];
    end
    
    for currentObject = 1:num
        currentDistance = norm(sceneDescriptors(currentObject,:) - cupDescriptor);
        tDist(v, currentObject) = currentDistance;
    end
    
end

% Plot
p = plot(values, tDist(:, 1:4))
axis([15 200 0 0.9])
legend('90degCup', 'car', 'normalCup', 'toasts')
title('Distance depending on the descriptor values');
xlabel('Number of descriptor values');
ylabel('Euclidean distance to the model');
set(p,'LineWidth',1.2)
detectionEdge = refline([0 0.1]);
set(detectionEdge,'LineStyle','--', 'Color', 'Black')

p = plot(values, tDist(:, 5:8))
axis([15 200 0 0.9])
legend('plate', 'frog', 'jar', '45degCup')
title('Distance depending on the descriptor values');
xlabel('Number of descriptor values');
ylabel('Euclidean distance to the model');
set(p,'LineWidth',1.2)
detectionEdge = refline([0 0.1]);
set(detectionEdge,'LineStyle','--', 'Color', 'Black')

